import React, { useState, useEffect, useImperativeHandle } from 'react';
import { Form, Input, Card, Select, message, Button, Switch } from 'antd';
import { size } from 'lodash';
import { connect } from 'umi';
import { dictionaryList } from '@/services/dictionary';
import BraftEditor from 'braft-editor';
import 'braft-editor/dist/index.css';
import OrganizationSelect from '@/components/OrganizationSelect';
import { RadioForm } from '../ScopeGroup';
import { FlowIconList, FlowIcon } from './components';

const { Option } = Select;

// 基础设置
const BasicSettingForm = React.forwardRef(({ form, dispatch, basicData, currentUser, tabName, id }, ref) => {
    const [categoryOptions, setCategoryOptions] = useState([]);
    const [messageModuleOptions, setMessageModuleOptions] = useState([]);
    const [iconTypeVisible, seticonTypeVisible] = useState(false);
    const [explanationIsInit, setExplanationIsInit] = useState(false);
    const { firstOrgInfo } = currentUser;
    const { firstCompanyCode } = firstOrgInfo;

    // 获取分类下拉
    const getCategoryOptions = async () => {
        const { data, code, msg } = await dictionaryList({ code: 'processCategory' });
        if (code === 10000) {
            const arr = [];
            if (data.length > 0) {
                data.forEach(item => {
                    arr.push({ value: item.dictValue, label: item.dictName });
                });
            }
            setCategoryOptions(arr);
        } else {
            message.error(msg);
        }
    };
    const getMessageModuleOptions = async () => {
        const { data, code, msg } = await dictionaryList({ code: 'messageModule' });
        if (code === 10000) {
            const arr = [];
            if (data.length > 0) {
                data.forEach(item => {
                    arr.push({ value: item.dictValue, label: item.dictName });
                });
            }
            setMessageModuleOptions(arr);
        } else {
            message.error(msg);
        }
    };

    const handleUpdate = () => {
        const values = form.getFieldsValue();
        const { scopeGroup, explanation, includeSubCompany } = values;

        const { scopeField } = scopeGroup;
        if (scopeField === 'company') {
            Object.assign(scopeGroup, { scopeLabel: ['全体员工'] });
        }

        dispatch({
            type: 'workFlowModel/basicDataSave',
            payload: {
                ...values,
                includeSubCompany: includeSubCompany === true ? 1 : 0,
                scopeGroup,
                explanation: explanation && explanation.toHTML() !== '<p></p>' ? explanation.toHTML() : ''
            }
        });
    };

    useImperativeHandle(ref, () => ({
        handleUpdate: typeString =>
            new Promise((resolve, reject) => {
                handleUpdate();
                // 获取companyName，备注：这个场景是后端需要冗余一个companyName字段，
                // 然后前端下拉树组件不触发onchange事件也要默认修改这个值，只能通过这种方式去获取了！
                const companyName = document.querySelector(
                    '#companyOrganizationSelect .ant-select-selection-selected-value'
                ).textContent;
                if (typeString === 'hold') {
                    // 暂存最少要填写流程名称和分类
                    if (size(form.getFieldValue('processName')) === 0) {
                        form.setFields({
                            processName: {
                                errors: [new Error('请输入审批名称')]
                            }
                        });
                        // eslint-disable-next-line prefer-promise-reject-errors
                        reject({ tabName });
                    } else if (!form.getFieldValue('category')) {
                        form.setFields({
                            category: {
                                errors: [new Error('请选择分组')]
                            }
                        });
                        // eslint-disable-next-line prefer-promise-reject-errors
                        reject({ tabName });
                    } else {
                        resolve({ formData: { ...basicData, companyName } });
                    }
                } else {
                    form.validateFields(err => {
                        if (err) {
                            // eslint-disable-next-line prefer-promise-reject-errors
                            reject({ tabName });
                        } else {
                            resolve({ formData: { ...basicData, companyName } });
                        }
                    });
                }
            })
    }));

    // 维护发起审批人同步
    useEffect(() => {
        handleUpdate();
    }, [JSON.stringify(form.getFieldsValue())]);

    useEffect(() => {
        if (form.getFieldValue('scopeGroup') !== basicData.scopeGroup) {
            form.setFieldsValue({ scopeGroup: basicData.scopeGroup });
        }
    }, [basicData.scopeGroup]);

    useEffect(() => {
        getCategoryOptions();
        getMessageModuleOptions();
        if (!id) {
            setExplanationIsInit(true);
        }
    }, []);

    useEffect(() => {
        if (size(basicData.explanation) > 0 && !explanationIsInit) {
            form.setFieldsValue({
                explanation: BraftEditor.createEditorState(basicData.explanation)
            });
            setExplanationIsInit(true);
        }
    }, [basicData.explanation]);

    return (
        <Card bordered={false} style={{ width: 750, margin: '16px 40px 25px' }}>
            <Form labelCol={{ span: 4 }} wrapperCol={{ span: 20 }}>
                <Form.Item label="审批名称" extra="最多50字">
                    {form.getFieldDecorator('processName', {
                        initialValue: basicData.processName || undefined,
                        rules: [
                            {
                                required: true,
                                message: '请输入审批名称'
                            }
                        ]
                    })(<Input maxLength={50} placeholder="请输入审批名称" />)}
                </Form.Item>
                <Form.Item label="适用公司">
                    <div id="companyOrganizationSelect">
                        {form.getFieldDecorator('organizationCode', {
                            initialValue: basicData.organizationCode || firstCompanyCode,
                            rules: [
                                {
                                    required: true,
                                    message: '请选择适用公司'
                                }
                            ]
                        })(<OrganizationSelect allowClear={false} />)}
                    </div>
                </Form.Item>
                <Form.Item label="是否覆盖子公司">
                    {form.getFieldDecorator('includeSubCompany', {
                        valuePropName: 'checked',
                        initialValue: basicData.includeSubCompany === 1 || false
                    })(<Switch />)}
                </Form.Item>
                <Form.Item label="选择分组">
                    {form.getFieldDecorator('category', {
                        initialValue: basicData.category || undefined,
                        rules: [
                            {
                                required: true,
                                message: '请选择分组'
                            }
                        ]
                    })(
                        <Select
                            placeholder="请选择分组"
                            allowClear
                            getPopupContainer={trigger => trigger.parentNode}
                            showSearch
                            optionFilterProp="children"
                        >
                            {size(categoryOptions) > 0 &&
                                categoryOptions.map(item => (
                                    <Option key={item.value} label={item.label}>
                                        {item.label}
                                    </Option>
                                ))}
                        </Select>
                    )}
                </Form.Item>

                {/* 通知类型产品说不要，不过感觉有不确定，等后面版本如果没用到直接删除吧╮(╯▽╰)╭ */}
                <Form.Item label="通知类型" style={{ display: 'none' }}>
                    {form.getFieldDecorator('messageModule', {
                        initialValue: basicData.messageModule || undefined
                        // rules: [
                        //     {
                        //         required: true,
                        //         message: '请选择类型'
                        //     }
                        // ]
                    })(
                        <Select placeholder="请选择类型" allowClear getPopupContainer={trigger => trigger.parentNode}>
                            {size(messageModuleOptions) > 0 &&
                                messageModuleOptions.map(item => (
                                    <Option key={item.value} label={item.label}>
                                        {item.label}
                                    </Option>
                                ))}
                        </Select>
                    )}
                </Form.Item>

                <Form.Item label="谁可以发起审批">
                    {form.getFieldDecorator('scopeGroup', {
                        initialValue: basicData.scopeGroup,
                        rules: [
                            {
                                validator(rule, value, callback) {
                                    if (value.scopeField !== 'company' && value.scopeValue.length === 0) {
                                        callback('请输入完整的必填项');
                                    }
                                    callback();
                                }
                            }
                        ]
                    })(<RadioForm organizationCode={form.getFieldValue('organizationCode')} />)}
                </Form.Item>
                <Form.Item label="模板图标">
                    {form.getFieldDecorator('iconType', {
                        initialValue: basicData.iconType || 'leave'
                    })(
                        <FlowIcon
                            onClick={() => {
                                seticonTypeVisible(true);
                            }}
                        />
                    )}
                    <Button
                        type="ghost"
                        onClick={() => {
                            seticonTypeVisible(true);
                        }}
                        style={{ marginLeft: 12 }}
                    >
                        选择图标
                    </Button>
                </Form.Item>
                <Form.Item
                    label="流程说明"
                    extra={
                        <span>
                            最多500字，当前输入
                            <b>
                                {form
                                    .getFieldValue('explanation')
                                    ?.toHTML()
                                    .replace(/<\/?.+?>/g, '').length || 0}
                            </b>
                            个字
                        </span>
                    }
                >
                    {form.getFieldDecorator('explanation', {
                        rules: [
                            {
                                validator(rule, value, callback) {
                                    try {
                                        const text = value?.toHTML().replace(/<\/?.+?>/g, '');
                                        if (text?.length > 500) {
                                            throw new Error('不能超过500个字');
                                        } else {
                                            callback();
                                        }
                                    } catch (err) {
                                        callback(err);
                                    }
                                }
                            }
                        ]
                    })(
                        <BraftEditor
                            controls={[
                                'font-size',
                                'line-height',
                                'letter-spacing',
                                'separator',
                                'text-color',
                                'bold',
                                'italic',
                                'separator',
                                'text-indent',
                                'text-align',
                                'separator',
                                'link',
                                'headings',
                                'list-ul',
                                'list-ol',
                                'separator',
                                'separator',
                                'separator',
                                'clear',
                                'remove-styles'
                            ]}
                            placeholder="请输入流程说明"
                            limitWidth={false}
                        />
                    )}
                </Form.Item>
                <Form.Item label="备注" extra="最多100字">
                    {form.getFieldDecorator('description', {
                        initialValue: basicData.description || undefined
                    })(<Input.TextArea maxLength={100} placeholder="请输入备注" />)}
                </Form.Item>
            </Form>
            <FlowIconList
                value={form.getFieldValue('iconType')}
                visible={iconTypeVisible}
                onCancel={() => {
                    seticonTypeVisible(false);
                }}
                onOk={e => {
                    form.setFieldsValue({ iconType: e });
                    seticonTypeVisible(false);
                }}
            />
        </Card>
    );
});

export default connect(({ workFlowModel, user }) => ({
    basicData: workFlowModel.basicData,
    currentUser: user.currentUser
}))(Form.create({ name: 'BasicSettingForm' })(BasicSettingForm));
